package com.fierce.cloud.ota.controller;

import com.fierce.cloud.core.web.ResultGenerator;
import com.fierce.cloud.core.web.responseDto.Response;
import com.fierce.cloud.ota.dao.UserRoleMapper;
import com.fierce.cloud.ota.model.User;
import com.fierce.cloud.ota.model.UserRole;
import com.fierce.cloud.ota.service.UserService;
import com.fierce.cloud.security.common.utils.CurrentUserUtils;
import com.fierce.cloud.security.entity.LoginRequest;
import com.fierce.cloud.security.service.AuthService;
import com.fierce.cloud.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

/**
 * @author: Fierce
 * @Date: 2021/2/6 22:13
 */
@RestController
@RequestMapping("/auth")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    AuthService authService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private CurrentUserUtils currentUserUtils;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/register")
    public Response userRegister(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.genFailResult("邮箱格式错误");
        }
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        try {
            userService.save(user);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("该用户名/邮箱已注册");
        }
        userRoleMapper.insertSelective(new UserRole(null, userService.findByUsername(user.getUsername()).getId(), 1));
        return ResultGenerator.genSuccessResult("注册成功");
    }

    @PostMapping("/login")
    public Response<String> userLogin(LoginRequest loginRequest) {
        String token = "";
        try {
            token = authService.getToken(loginRequest);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("登陆失败。用户名或密码错误");
        }
        return ResultGenerator.genSuccessResult("登陆成功", token);
    }

    @GetMapping("/logout")
    public Response userLogout() {
        Optional.ofNullable(currentUserUtils.getCurrentUser()).orElseThrow(() -> new UsernameNotFoundException("找不到用户"));
        redisUtil.delete(currentUserUtils.getCurrentUser().getId().toString());
        return ResultGenerator.genSuccessResult("退出成功");
    }

    @GetMapping("/info")
    public Response<User> getUserInfo() {
        User currentUser = currentUserUtils.getCurrentUser();
        currentUser.setPassword(null);
        return ResultGenerator.genSuccessResult(currentUser);
    }
}
